package info.amber.vboot.kafka.service;


import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Slf4j
@Service
public class KafkaService {
    public static final String TOPIC_TEST = "test-topic.t";
    public static final String GROUP_ID = "testTopicGroupId";

    @Autowired
    private KafkaTemplate kafkaTemplate;

    public void send(String topic, String msg) {
        log.info("{} {}", topic, msg);
        kafkaTemplate.send(topic, msg);
    }

    @KafkaListener(topics = {KafkaService.TOPIC_TEST}, groupId = KafkaService.GROUP_ID)
    public void onMessage(ConsumerRecord<?, String> record, @Payload Object msg, @Headers MessageHeaders headers) {

        headers.keySet().forEach(key -> {
            log.info("{} {}", key, headers.get(key));
        });
        log.info("{}", msg);
        Optional<String> kafkaRecord = Optional.ofNullable(record.value());
        if (kafkaRecord.isPresent()) {
            String data = kafkaRecord.get();
            log.info("consume {}", data);
        }

    }
}
